package com.cs4261.smartalarm.backend;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.cs4261.smartalarm.frontend.CreateAlarmActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class AlarmService extends Service {
	private Context context;
	private AlarmsDatabaseHelper alarmDBHelper;
	private WeatherHelper weatherHelper;
	
	@Override
	public void onCreate() {
		// code to execute when the service is first created
		alarmDBHelper = new AlarmsDatabaseHelper(getApplicationContext());
		weatherHelper = new WeatherHelper(getApplicationContext());
	}

	@Override
	public void onStart(Intent intent, int startid) {
		// code to execute when the service is starting up
		alarmDBHelper.open();
		List<Alarm>  alarmList = alarmDBHelper.getAllAlarms();
		alarmDBHelper.close();
		for(Alarm alarm : alarmList) {
			if(alarm.getActive() == 1) {
				Date dat = new Date();// initializes to now
				Calendar cal_alarm = Calendar.getInstance();
				Calendar cal_now = Calendar.getInstance();
				cal_now.setTime(dat);
				cal_alarm.setTime(dat);
				cal_alarm.set(Calendar.HOUR_OF_DAY, alarm.getHour());// set the alarm time
				cal_alarm.set(Calendar.MINUTE, alarm.getMinute());
				cal_alarm.set(Calendar.SECOND, 0);
				if (cal_alarm.before(cal_now)) {// if its in the past increment
					cal_alarm.add(Calendar.DATE, 1);
				}

				Intent AlarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
				AlarmIntent.putExtra("alarm_id", alarm.getId());
				AlarmManager AlmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
				PendingIntent Sender = PendingIntent.getBroadcast(getApplicationContext(), (int)alarm.getId(), AlarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
				AlmMgr.set(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), Sender);
			}
		}
		
		//Toast.makeText(getApplicationContext(), weatherHelper.getCurrentWeatherCondition(), Toast.LENGTH_LONG).show();
	}

	@Override
	public void onDestroy() {
		// code to execute when the service is shutting down
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}